package com.mtz.service.impl;

import com.mtz.enums.DeleteEnum;
import com.mtz.exception.MtzException;
import com.mtz.form.QuesAnsForm;
import com.mtz.service.ExcelService;
import com.mtz.service.QuesAnsService;
import com.mtz.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author 煜赜
 * @date 2018/12/22 15:03
 */
@Service
@Slf4j
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    QuesAnsService quesAnsService;

    @Override
    public boolean batchImport(String fileName, MultipartFile file, String author) throws Exception {

        boolean notNull = false;
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MtzException(-1,"上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        QuesAnsForm quesAnsForm;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            quesAnsForm = new QuesAnsForm();
            Cell cell = row.getCell(0);
            Integer id = null;
            if (cell != null) {
                id = (int) row.getCell(0).getNumericCellValue();
            }
            Integer knowledgeType = (int) row.getCell(1).getNumericCellValue();
            String question = row.getCell(2).getStringCellValue();
            String keyword = row.getCell(3).getStringCellValue();
            String answer = row.getCell(4).getStringCellValue();
            Integer angel = (int) row.getCell(5).getNumericCellValue();


            if(id != null){
                quesAnsForm.setId(Integer.valueOf(id));
            }
            quesAnsForm.setKnowledgeType(Integer.valueOf(knowledgeType));
            quesAnsForm.setQuestion(question);
            quesAnsForm.setKeyword(keyword);
            quesAnsForm.setAnswer(answer);
            quesAnsForm.setAuthor(author);
            quesAnsForm.setAngle(Integer.valueOf(angel));
            quesAnsForm.setIsDeleted(DeleteEnum.PUBLISH.getCode());

            log.info("导入数据:{}", JsonUtil.toJson(quesAnsForm));

            if(id == null){
                quesAnsService.addQuesAns(quesAnsForm);
            } else { //修改数据
                quesAnsService.editQuesAns(quesAnsForm);
            }

        }

        return true;
    }

    @Override
    public void createTitle(HSSFWorkbook workbook, HSSFSheet sheet) {
        HSSFRow row = sheet.createRow(0);
        //设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
        sheet.setColumnWidth(1,12*256);
        sheet.setColumnWidth(3,17*256);

        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBold(true);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setFont(font);

        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("id");
        cell.setCellStyle(style);


        cell = row.createCell(1);
        cell.setCellValue("knowledgeType");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("question");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("keyword");
        cell.setCellStyle(style);

        cell = row.createCell(4);
        cell.setCellValue("answer");
        cell.setCellStyle(style);

        cell = row.createCell(5);
        cell.setCellValue("author");
        cell.setCellStyle(style);

        cell = row.createCell(6);
        cell.setCellValue("angle");
        cell.setCellStyle(style);
    }

    @Override
    public void buildExcelFile(String filename, HSSFWorkbook workbook) throws Exception {
        FileOutputStream fos = new FileOutputStream(filename);
        workbook.write(fos);
        fos.flush();
        fos.close();
    }

    @Override
    public void buildExcelDocument(String filename, HSSFWorkbook workbook, HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "utf-8"));
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
